﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMovement : MonoBehaviour
{

    public float defense = 2;       // 防御
    public float maxHP = 100;       // 最大生命
    public float speed = 2;         // 移动速度

    [Header("受伤效果持续时间")]
    [SerializeField]
    private float hurtEffectTime = 0.15f;       // 受伤效果持续
    private float hurtEffectCounter;            // 计数器，初始为 hurtEffectTime 每帧递减

    [Header("死亡效果")]
    public GameObject deathEffectPrefab;

    [Header("受伤害数字")]
    public GameObject damgeNumPrefab;
    public float damageOffsetY = 0.2f;     // 伤害数字显示的Y轴偏移量

    private float HP;       // 当前生命

    private Rigidbody2D rb;
    private SpriteRenderer sr;
    private GameObject playerGo;
    private GameObject damageCanvasGo;

    void Start()
    {
        HP = maxHP;

        rb = GetComponent<Rigidbody2D>();
        sr = GetComponent<SpriteRenderer>();

        playerGo = GameObject.Find("Player");
        damageCanvasGo = GameObject.Find("Canvas");

        Debug.Log($"Enemy: {sr.bounds.size}");
    }



    void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, playerGo.transform.position, speed * Time.deltaTime);

        if (hurtEffectCounter <= 0)
        {
            sr.material.SetFloat("_FlashAmount", 0);
        }
        else
        {
            hurtEffectCounter -= Time.deltaTime;
        }
    }

    // 受伤
    public void Injured(float damage, float knockback)
    {
        float finalDamage = damage - defense;
        if (finalDamage < 0)
        {
            finalDamage = 0;
        }
        Debug.Log($"Injured damage:{damage}, -HP:{finalDamage}");

        HP -= finalDamage;


        ShowDamage(finalDamage);
        InjuredShader();
        KnockbackEffect(knockback);

        if (HP <= 0)
        {
            Instantiate(deathEffectPrefab, transform.position, Quaternion.identity);
            Destroy(gameObject);
        }
    }

    private void InjuredShader()
    {
        sr.material.SetFloat("_FlashAmount", 1);
        hurtEffectCounter = hurtEffectTime;
    }

    // 击退效果
    private void KnockbackEffect(float knockback)
    {
        // 敌人向量 - 玩家向量 = 玩家向敌人方向向量，在通过归一化后，乘以击退倍率，最终是击退距离
        Vector2 distance = (transform.position - playerGo.transform.position).normalized * knockback;
        transform.position = new Vector2(transform.position.x + distance.x, transform.position.y + distance.y);
    }

    // 显示受伤害数字
    private void ShowDamage(float damage)
    {
        Vector3 numPosition = new Vector3(transform.position.x, transform.position.y + damageOffsetY, transform.position.z);
        GameObject damageNumGo = Instantiate(damgeNumPrefab, numPosition, Quaternion.identity);
        damageNumGo.transform.SetParent(damageCanvasGo.transform);
        damageNumGo.transform.localScale = new Vector3(1, 1, 1);

        DamageNum damageNum = damageNumGo.GetComponent<DamageNum>();
        damageNum.ShowDamage(damage);
    }
}
